package com.yzf.demo.demo.Thread.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by 于占峰 on 2020/4/4/004.
 * 假设线程进行文件导入导出服务
 */
public class CyclicBarrierDemo1 extends Thread {
    private String path;

    //定义一个成员变量
    private CyclicBarrier cyclicBarrier;


    public CyclicBarrierDemo1(String path, CyclicBarrier cyclicBarrier) {
        this.cyclicBarrier = cyclicBarrier;
        this.path = path;
    }

    @Override
    public void run() {
        System.out.println("导入导出文件:" + path);
        //执行业务后调用CyclicBarrier阻塞此子线程
        try {
            //cyclicBarrier.await();
            try {
                //为了避免运行的子线程不够 无法唤醒所有阻塞的子线程 可以传入超时时间 超时后抛出异常
                cyclicBarrier.await(10L, TimeUnit.SECONDS);
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}
